package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿管理,收货地址
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 保存新增地址
     * @param addressBook  新增得地址信息
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        //输出调试日志
        log.info("地址保存功能……地址：{}",addressBook.toString());

        //在 filter 过滤器中，设置了每一个页面得 ThreadLocalId 为 userId
        //将和用户表得 关系表 信息完善
        addressBook.setUserId(BaseContext.getCurrentThreadId());
        //更新 地址 表得信息
        addressBookService.save(addressBook);

        //返回数据到前端，进行展示
        return R.success(addressBook);
    }

    /**
     * 设置默认地址得功能
     * @param addressBook  选择得默认地址得信息对象,只传送了地址对应得id，足够了
     * @return
     */
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        //输出调试日志
        log.info("addressBook:{}", addressBook);

        //先将所有得地址全部设置为 不是默认 0，再将当前选择得地址设置为 默认 1
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        //当前登录用户得 id 已经保存到了 ThreadLocal 中（filter过滤器设置得）
        //通过 地址簿数据表 查询 当前登录用户id 对应得地址信息
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentThreadId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        //将当前选择得地址信息设置为 1 默认，里面有选择得 地址得id
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        //输出调试日志
        log.info("通过id查询地址，id：{}",id);

        //查询 地址
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        } else {
            return R.error("没有找到该对象");
        }
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {
        //输出调试日志
        log.info("查询默认地址功能……");

        //创建条件构造器，通过 userId 查询所有地址，默认 1 进行筛选
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentThreadId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

    /**
     * 查询指定用户的全部地址
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        //输出日志调试
        log.info("查询全部地址");

        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != BaseContext.getCurrentThreadId(), AddressBook::getUserId, BaseContext.getCurrentThreadId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc
        return R.success(addressBookService.list(queryWrapper));
    }
}
